<template>
  <div style="display: flex;flex-direction: column;justify-items: center;align-items: center">
    <h4>订单编号:{{ serial }}</h4>
    <div style="display: flex;flex-direction: column;justify-items: center;align-items: center">
      <el-button icon="el-icon-s-platform" type="primary" style="width: 200px; margin-top: 40px;margin-left: 10px"
                 @click="importImages">
        上传图片
      </el-button>
      <el-button icon="el-icon-s-platform" type="primary" style="width: 200px;margin-top: 40px" @click="importAudio">
        上传录音
      </el-button>
    </div>

    <el-dialog
      :title="image.title"
      :visible.sync="image.open"
      width="400px"
      append-to-body
      :close-on-click-modal="!image.isUploading"
      :show-close="!image.isUploading"
    >
      <el-upload
        action="#"
        ref="image"
        :limit="5"
        :on-exceed="imageExceed"
        accept=".jpg, .png"
        :headers="image.headers"
        :disabled="image.isUploading"
        :on-change="imageFileChange"
        :before-upload="imageBeforeUpload"
        :auto-upload="false"
        list-type="picture"
        drag

        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入jpg, png格式文件,最多5张图片。</span>
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImageForm" :loading="image.isUploading" :disabled="image.isUploading">
          {{ image.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button @click="image.open = false" :disabled="image.isUploading">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog
      :title="audio.title"
      :visible.sync="audio.open"
      width="400px"
      append-to-body
      :close-on-click-modal="!audio.isUploading"
      :show-close="!audio.isUploading">
      <el-upload
        action="#"
        ref="audio"
        :limit="3"
        :on-exceed="audioExceed"
        accept=".wav,.mp3,.m4a"
        :headers="audio.headers"
        :disabled="audio.isUploading"
        :on-change="audioFileChange"
        :before-upload="audioBeforeUpload"
        :auto-upload="false"
        drag
        multiple
        :show-file-list="showAudioFileList"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入mp3/wav/m4a格式文件,每个小于5M,最多3段录音</span>
        </div>
      </el-upload>

      <div v-if="audio.uploadFiles.length > 0" style="margin-top: 5px;">
        <div v-for="(file, index) in audio.uploadFiles" :key="index" style="margin-bottom: 10px;">
          <div>{{ file.name }}</div>
          <div style="display: flex; justify-items: center;align-items: center">
            <audio controls :src="getAudioUrl(file)"></audio>
            <el-button type="danger" @click="removeAudio(index)" style="margin-left: 4px">删除</el-button>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudioForm" :loading="audio.isUploading" :disabled="audio.isUploading">
          {{ audio.isUploading ? '上传中...' : '确 定' }}
        </el-button>
        <el-button @click="audio.open = false" :disabled="image.isUploading">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {uploadOrderAudios, uploadOrderImages} from "@/api/hmk/order";
import {getToken} from "@/utils/auth";

export default {
  name: 'QrcodeRedirect',
  mounted() {
    const {orderId, followId, userId, serial} = this.$route.query;
    console.log('orderId,followId,userId', orderId, followId, userId);
    this.orderId = orderId;
    this.followId = followId;
    this.userId = userId;
    this.serial = serial;
    this.audioPlayer = new Audio();
  },
  data() {

    return {
      showAudioFileList: false,
      audioPlayer: null,
      currentPreviewIndex: null,
      isPlaying: false,
      serial: null,
      orderId: null,
      followId: null,
      userId: null,
      imageResUrls: [],
      // 导入参数
      image: {
        uploadFiles: [],
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
      },
      audioResUrls: [],
      audio: {
        uploadFiles: [],
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
      },

    }
  },
  methods: {

    getAudioUrl(file) {
      console.log('raw', file.raw)
      // 如果是新选择的文件（File对象）
      if (file.raw) {
        return URL.createObjectURL(file.raw);
      }
      // 如果是已经上传的文件（可能有远程URL）
      return file.url || '';
    },

    audioFileChange(file, fileList) {
      this.audio.uploadFiles = fileList;
    },

    removeAudio(index) {
      this.audio.uploadFiles.splice(index, 1);
    },
    importAudio() {
      this.showAudioFileList = null;
      this.audioResUrls = [];
      this.audio.uploadFiles = [];
      this.audio.title = "上传录音";
      this.audio.open = true;
    },
    importImages() {
      this.imageResUrls = [];
      this.image.uploadFiles = [];
      this.image.title = "上传图片";
      this.image.open = true;
    },
    audioExceed(files, fileList) {
      return this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    imageExceed(files, fileList) {
      return this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    audioBeforeUpload(file) {
      const isAudio = ['audio/mpeg', 'audio/wav', 'audio/mp4', 'audio/x-m4a'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isAudio) {
        return this.$message.error('录音只能是 mp3/wav/m4a格式!');
      }
      if (!isLt5M) {
        return this.$message.error('录音大小不能超过 5MB!');
      }
      return isAudio && isLt5M;
    },

    imageBeforeUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        return this.$message.error('图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        return this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    submitAudioForm() {
      if (this.audio.uploadFiles.length === 0) {
        this.$message.warning("请先选择文件");
        return;
      }
      if ((this.audio.uploadFiles.length + this.audioResUrls.length) > 3) {
        this.$message.warning("你本次上传的总数大于3,请删除一些");
        return;
      }
      const formData = new FormData();
      this.audio.uploadFiles.forEach(file => {
        formData.append("files", file.raw);
      });
      formData.append("orderId", this.orderId);
      formData.append("followId", this.followId);
      formData.append("userId", this.userId);
      formData.append("userId", this.$store.state.user.id);

      // 3. 显示上传状态
      this.audio.isUploading = true;
      const progressMessage = this.$message({message: '文件上传中...', type: 'info', duration: 0, showClose: true});
      // 4. 调用上传API（带进度监控）
      uploadOrderAudios(formData, {
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
            console.log(`上传进度: ${percent}%`);
          }
        }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success("上传成功！");
          this.audio.uploadFiles = [];
          this.audio.open = false;
          this.audioResUrls = [...res.data.urls, ...this.audioResUrls];
        } else {
          this.$message.error(res.msg || "上传失败");
        }
      }).catch(error => {
        this.$message.error("请求失败: " + (error.message || "未知错误"));
      }).finally(() => {
        this.audio.isUploading = false;
        progressMessage.close();
      });
    },


    submitImageForm() {
      if (this.image.uploadFiles.length === 0) {
        this.$message.warning("请先选择文件");
        return;
      }
      if ((this.image.uploadFiles.length + this.imageResUrls.length) > 5) {
        this.$message.warning("你本次上传的总数大于5,请删除一些");
        return;
      }
      const formData = new FormData();
      this.image.uploadFiles.forEach(file => {
        formData.append("files", file.raw);
      });
      formData.append("orderId", this.orderId);
      formData.append("followId", this.followId);
      formData.append("userId", this.userId);
      formData.append("userId", this.$store.state.user.id);
      // 3. 显示上传状态
      this.image.isUploading = true;
      const progressMessage = this.$message({message: '文件上传中...', type: 'info', duration: 0, showClose: true});
      // 4. 调用上传API（带进度监控）
      uploadOrderImages(formData, {
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
            console.log(`上传进度: ${percent}%`);
          }
        }
      }).then(res => {
        if (res.code === 200) {
          this.$message.success("上传成功！");
          this.image.uploadFiles = [];
          this.image.open = false;
          this.imageResUrls = [...res.data.urls, ...this.imageResUrls];
        } else {
          this.$message.error(res.msg || "上传失败");
        }
      }).catch(error => {
        this.$message.error("请求失败: " + (error.message || "未知错误"));
      }).finally(() => {
        this.image.isUploading = false;
        progressMessage.close();
      });
    },


    imageFileChange(file, fileList) {
      this.image.uploadFiles = fileList;
    },
  }
};
</script>

<!--<style lang="scss" scoped>-->

<!--.el-button {-->
<!--  flex: 1;-->
<!--  width: 100%;-->
<!--}-->
<!--</style>-->
